package edu.jmu.transmissionassistant.activity

import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import edu.jmu.transmissionassistant.adapter.RvAdapter
import edu.jmu.transmissionassistant.component.*
import edu.jmu.transmissionassistant.databinding.ActivityMainBinding
import edu.jmu.transmissionassistant.model.UploadFileInfo
import edu.jmu.transmissionassistant.util.NetUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * TODO 完成手机界面：点击按钮开关服务器
 *  mServerManager.startServer() and mServerManager.stopServer()
 */
class MainActivity : AppCompatActivity(), ServerLifecycle {
    private lateinit var mServerManager: ServerManager
    private lateinit var binding: ActivityMainBinding
    private val PERMISSIONS_STORAGE = arrayOf(
        "android.permission.READ_EXTERNAL_STORAGE",
        "android.permission.WRITE_EXTERNAL_STORAGE",
        "android.permission.INTERNET"
    )

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // register main activity's lifecycle as global default lifecycle
        AppConfig.mainScope = lifecycleScope
        this.binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(this.binding.root)
        // AndServer run in the service.
        mServerManager = ServerManager(this)
        mServerManager.register()
        binding.control.setOnCheckedChangeListener { _, isChecked ->
            run {
                if (isChecked) {
                    mServerManager.startServer()
                    binding.ipTv.text = "访问IP为：${NetUtils.localIPAddress}"
                } else {
                    mServerManager.stopServer()
                    binding.ipTv.text = "服务暂未开启"
                }
            }
        }


        val uploadFiles: ArrayList<UploadFileInfo> = ArrayList()
        binding.recycleView.layoutManager=LinearLayoutManager(this@MainActivity,RecyclerView.VERTICAL,false)
        val adapter=RvAdapter(uploadFiles)
        binding.recycleView.adapter= adapter
        binding.recycleView.addItemDecoration(DividerItemDecoration(this,DividerItemDecoration.VERTICAL))

        requestAllPermissions()
        launch(Dispatchers.IO) {
            startSubscribe(uploadFiles,adapter)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private suspend fun startSubscribe(uploadFiles: ArrayList<UploadFileInfo>, adapter: RvAdapter) {
        while(true){
            val uploadFile=MessageBus.instance().subscribe(AppConfig.UPLOAD_PATH)
            //TODO subscribe uploaded logs
            withContext(Dispatchers.Main) {
                //TODO output to ui
                uploadFiles.add(uploadFile)
                adapter.notifyDataSetChanged()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mServerManager.unRegister()
    }

    /**
     * Start notify.
     */
    override fun onServerStart(ip: String) {
        Toast.makeText(this, "启动成功", Toast.LENGTH_SHORT).show()
    }

    /**
     * Error notify.
     */
    override fun onServerError(message: String) {
        Toast.makeText(this, "启动失败,$message", Toast.LENGTH_SHORT).show()
    }

    /**
     * Stop notify.
     */
    override fun onServerStop() {
        Toast.makeText(this, "关闭成功", Toast.LENGTH_SHORT).show()
    }

    private fun requestAllPermissions(){
        val permissionList: ArrayList<String> = ArrayList()
        for (s in PERMISSIONS_STORAGE) {
            if(ContextCompat.checkSelfPermission(this,s)!= PackageManager.PERMISSION_GRANTED){
                permissionList.add(s)
            }
        }

        if (permissionList.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toTypedArray(), 1002)
        }
    }
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1002 ->    {
                if(grantResults.isNotEmpty()){
                    for( grantResult in grantResults){
                        if(grantResult != PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(this, "本应用需要获取您的手机存储权限以确保功能正常使用", Toast.LENGTH_SHORT).show()
                            return
                        }
                    }
                }
            }



        }
    }

}